import com.hc.jatpacklib.data.entity.YcDataSourceEntity
import com.hc.pluginlabour.net.NetCode
import com.hcc.plugindust.net.HttpResponse
import com.hcc.plugindust.net.HttpResponseList
import com.yc.jetpacklib.data.constant.YcNetErrorCode
import com.yc.jetpacklib.exception.YcException
import com.yc.jetpacklib.extension.toPageSum
import com.yc.jetpacklib.extension.ycIsEmpty


import com.yc.jetpacklib.mapper.IMapper

/**
 * SimpleDes:
 * Creator: Sindi
 * Date: 2021-02-19
 * UseDes:检测返回参数的code正确和分页里data是否为空
 */


/**
 * 检测返回参数的code正确
 */
fun <T> HttpResponse<T>.checkCode(): HttpResponse<T> {
    return when (code) {
        NetCode.NET_CODE_SUCCESS ->
            this
        NetCode.NET_CODE_TOKEN_INVALID -> {
           // LoginActivity.newInstance(YcActivityManager.getCurrentActivity()!!,true)
            this
        }
        else -> {
            throw YcException(message, code)
        }
    }
}


/**
 * 检测返回参数的code正确
 */
fun <T> HttpResponseList<T>.checkCode(): HttpResponseList<T> {
    return when (code) {
        NetCode.NET_CODE_SUCCESS ->
            this
        NetCode.NET_CODE_TOKEN_INVALID -> {
           // LoginActivity.newInstance(YcActivityManager.getCurrentActivity()!!,true)
            this
        }
        else -> {
            throw YcException(message, code)
        }
    }
}


/**
 * 获取非空的data
 */
fun <T> HttpResponse<T?>.ycGetDataNoNull(): T {
    checkCode()
    return data?: throw YcException(message, code)
}


/**
 * 检测数据（总页数）
 */
fun <T, R> HttpResponseList<T>.checkListDataPageSum(map: IMapper<T, R>): YcDataSourceEntity<R> {
    checkCode()
    return when {
        data.ycIsEmpty() -> {
            throw YcException(message, YcNetErrorCode.DATE_NULL)
        }
        else -> {
            val dataModel = data!!.map {
                map.map(it)
            }
            YcDataSourceEntity(dataModel, totalNum)
        }
    }
}

/**
 * 检测数据（数据总数）
 */
fun <T, R> HttpResponseList<T>.checkListDataTotal(map: IMapper<T, R>, pageSize: Int = 30): YcDataSourceEntity<R> {
    checkCode()
    return when {
        data.ycIsEmpty() -> {
            throw YcException(message, YcNetErrorCode.DATE_NULL)
        }
        else -> {
            val dataModel = data!!.map {
                map.map(it)
            }
            YcDataSourceEntity(dataModel, totalNum.toPageSum(pageSize))
        }
    }
}


fun <T, R> HttpResponse<List<T>>.checkListData(map: IMapper<T, R>): List<R> {
    checkCode()
    return when {
        data.ycIsEmpty() -> {
            throw YcException(message, YcNetErrorCode.DATE_NULL)
        }
        else -> {
            data!!.map {
                map.map(it)
            }
        }
    }
}


